<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class keping extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->library('flexigrid');
        $this->load->library('form_validation');
		$this->load->library('session');
        $this->load->helper('flexigrid');
        $this->load->helper(array('form', 'url'));
        $this->load->model('keping_model');
        $this->load->model('jalan_model');
        $this->load->model('jalan_periode_model');
    }

    //load Grid
    function index($no_ruas) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
			$colModel['KEPING'] = array('Keping Jalan', 150, TRUE, 'center', 1);
            $colModel['NILAI_IRI'] = array('Nilai Iri', 100, TRUE, 'center', 1);
            $colModel['POSISI_KM'] = array('Posisi Km', 70, TRUE, 'center', 1);
            $colModel['TIPE'] = array('Tipe', 70, TRUE, 'center', 1);
            $colModel['LEBAR'] = array('Lebar', 70, TRUE, 'center', 1);
            $colModel['Edit'] = array('Perbarui', 70, TRUE, 'center', 1);
            $colModel['Penanganan'] = array('Penanganan', 70, TRUE, 'center', 1);

			
			//get nama jalan
			$hasil = $this->jalan_model->selectone($no_ruas);
			foreach ($hasil->result() as $row) {
                $nama_ruas_jalan = $row->NAMA_RUAS_JALAN;
            }
			$this->session->set_userdata('no_ruas', $no_ruas);
			$this->session->set_userdata('nama_ruas_jalan', $nama_ruas_jalan);

            $gridParams = array(
                'width' => 'auto',
                'height' => 300,
                'rp' => 15,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Keping Jalan</br>Periode : '.$this->session->userdata('nama_periode').'</br>Ruas Jalan : '.$nama_ruas_jalan.'',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('Generate Segmen Keping Jalan', 'update', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Tambah Keping Jalan', 'add', 'spt_js');
            $buttons[] = array('separator');
			$buttons[] = array('Cetak Keping Jalan', 'print', 'spt_js');
            $buttons[] = array('separator');
			$buttons[] = array('Hapus', 'delete', 'spt_js');
			$buttons[] = array('separator');
			$buttons[] = array('Input Penanganan Masal', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Kembali ke daftar ruas jalan', 'back', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_berkas
            $grid_js = build_grid_js('flex1', site_url("keping/grid/".$no_ruas."/".$this->session->userdata('id_periode').""), $colModel, 'KEPING', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
        function spt_js(com,grid)
        {
                if (com=='Tambah Keping Jalan')
                {
                        location.href='" . base_url() . "index.php/keping/form';
                }
				
				if (com=='Generate Segmen Keping Jalan')
                {
                        location.href='" . base_url() . "index.php/keping_segmen/generate_segmen';
                }
                
                if (com=='Input Penanganan Masal')
                {
                        location.href='" . base_url() . "index.php/penanganan/form_masal';
                }
				
				if (com=='Cetak Keping Jalan')
                {
                        location.href='" . base_url() . "index.php/keping/form_cetak_keping';
                }
				
				if (com=='Kembali ke daftar ruas jalan')
                {
                        location.href='" . base_url() . "index.php/jalan_periode/index/".$this->session->userdata('id_periode')."';
                }

                if (com=='Hapus')
                        {
                           if($('.trSelected',grid).length>0){
                                   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' keping jalan?')){
                                                var items = $('.trSelected',grid);
                                                var itemlist ='';
                                                for(i=0;i<items.length;i++){
                                                        itemlist+= items[i].id.substr(3)+',';
                                                }
                                                $.ajax({
                                                   type: 'POST',
                                                   url: '" . base_url() . "index.php/keping/delete" . "',
                                                   data: 'items='+itemlist,
                                                   success: function(data){
                                                        $('#flex1').flexReload();
                                                   }
                                                });
                                        }
                                } else {
                                        return false;
                                }
                        }

        }
        </script>
        ";


            $data['js_grid'] = $grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid($no_ruas, $id_periode) {
        $valid_fields = array('KEPING', 'NILAI_IRI', 'POSISI_KM', 'TIPE');
        $this->flexigrid->validate_post('KEPING', 'asc', $valid_fields);
        $records = $this->keping_model->get_data($no_ruas, $id_periode);
        $this->output->set_header($this->config->item('json_header'));
        $no = 0;

        foreach ($records['records']->result() as $row) {
            $record_items[] = array(
                $row->ID_KEPING,
                $no = $no + 1,
                $row->KEPING,
				$row->NILAI_IRI,
                $row->POSISI_KM,
                $row->TIPE,
                $row->LEBAR,
                '<a href=\'' . base_url() . 'index.php/keping/edit/' . $row->ID_KEPING. '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/edit.png\'></a> ',
                '<a href=\'' . base_url() . 'index.php/penanganan/index/' . $row->ID_KEPING. '\'><img border=\'0\' src=\'' . base_url() . 'images/grid/penanganan.png\'></a> ',
            );
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }
    
    
    
    function form() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			//$data['ustad'] = $this->ustad_model->get_data_all_ustad();
            $data['content'] = $this->load->view('form_keping', $data, true);
            $this->load->view('main', $data);
        }
    }
	
    
	
	function add() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
			if($this->cek_validasi() != false)
			{
				$this->form();
			}
			else{
				$data = array(
					'KEPING' => $this->input->post('keping'),
					'NILAI_IRI' => $this->input->post('nilai_iri'),
					'POSISI_KM' => $this->input->post('posisi_km'),
					'TIPE' => $this->input->post('tipe'),
					'LEBAR' => $this->input->post('lebar'),
					'NO_RUAS' => $this->session->userdata('no_ruas'),
					'ID_PERIODE' => $this->session->userdata('id_periode')
				);
				$this->keping_model->insert($data);
				redirect('keping/index/'.$this->session->userdata('no_ruas').'');
			}
        }
    }

    public function edit($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'edit';
            $record_artikel = $this->keping_model->selectone($id);
            foreach ($record_artikel->result() as $artikel){
                $data['id_keping'] = $artikel->ID_KEPING;
                $data['keping'] = $artikel->KEPING;
                $data['nilai_iri'] = $artikel->NILAI_IRI;
                $data['posisi_km'] = $artikel->POSISI_KM;
                $data['tipe'] = $artikel->TIPE;
                $data['lebar'] = $artikel->LEBAR;
                $data['no_ruas'] = $artikel->NO_RUAS;
            }
            $data['failed'] = false;
            $data['aa'] = '';
            $data['content'] = $this->load->view('form_keping', $data, true);
            $this->load->view('main', $data);
        }
    }

    function update($id) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
			if($this->cek_validasi() != false)
				{
					$this->edit($id);
				}
				else{
					$data = array(
						'KEPING' => $this->input->post('keping'),
						'NILAI_IRI' => $this->input->post('nilai_iri'),
						'POSISI_KM' => $this->input->post('posisi_km'),
						'TIPE' => $this->input->post('tipe'),
						'LEBAR' => $this->input->post('lebar')
					);
					$data = str_replace("'", "\'", $data);
					$this->keping_model->update($id, $data);
					redirect('keping/index/'.$this->session->userdata('no_ruas').'');
				}
        }
    }

    
    function delete() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $spt_ids_post_array = explode(",", $this->input->post('items'));
            foreach ($spt_ids_post_array as $index => $id) {
                if (isset($id) && $id != '') {
                    $this->keping_model->delete($id);
                }//end if
            }//end foreach
        }
    }
	
	
	
	function form_cetak_keping() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			//$data['ustad'] = $this->ustad_model->get_data_all_ustad();
            $data['content'] = $this->load->view('form_cetak_keping', $data, true);
            $this->load->view('main', $data);
        }
    }
	
	
	function cetak_keping(){
		//get data jalan
		$id_periode = $this->session->userdata('id_periode');
		$no_ruas = $this->session->userdata('no_ruas');
		$data['tahun_awal'] = $this->input->post('awal');
		$data['tahun_ahir'] = $this->input->post('ahir');
		$data['data_keping'] = $this->keping_model->get_data_keping($id_periode, $no_ruas);
		$data['no_ruas'] = $no_ruas;
		$data['nama_ruas_jalan'] = $this->session->userdata('nama_ruas_jalan');
		$hasil = $this->jalan_model->selectone($no_ruas);
		foreach ($hasil->result() as $row) {
			$data['panjang_jalan'] = $row->PANJANG;
			$data['gps_awal_lat'] = $row->GPS_AWAL_LAT;
			$data['gps_awal_long'] = $row->GPS_AWAL_LONG;
			$data['gps_akhir_lat'] = $row->GPS_AKHIR_LAT;
			$data['gps_akhir_long'] = $row->GPS_AKHIR_LONG;
		}
		//end get data jalan
		
		$data['nama_periode'] = $this->session->userdata('nama_periode');
		$data['mulai'] = $this->session->userdata('selesai');
		$data['selesai'] = $this->session->userdata('mulai');
		//$data['nama_kelas'] = $this->session->userdata('nama_kelas');
		
		//hitung total km merah
		$tot_km_merah = $this->db->query("SELECT SUM(NILAI_IRI) as hasil FROM keping_jalan where NO_RUAS = ".$no_ruas." AND NILAI_IRI >= 12");
		foreach ($tot_km_merah->result() as $row) {
			$data['tot_km_merah'] = $row->hasil;
		}
		
		//hitung total km orange
		$tot_km_orange = $this->db->query("SELECT SUM(NILAI_IRI) as hasil FROM keping_jalan where NO_RUAS = ".$no_ruas." AND NILAI_IRI >= 8 AND NILAI_IRI < 12");
		foreach ($tot_km_orange->result() as $row) {
			$data['tot_km_orange'] = $row->hasil;
		}
		
		//hitung total km kuning
		$tot_km_kuning = $this->db->query("SELECT SUM(NILAI_IRI) as hasil FROM keping_jalan where NO_RUAS = ".$no_ruas." AND NILAI_IRI >= 4 AND NILAI_IRI < 8");
		foreach ($tot_km_kuning->result() as $row) {
			$data['tot_km_kuning'] = $row->hasil;
		}
		
		//hitung total km hijau
		$tot_km_hijau = $this->db->query("SELECT SUM(NILAI_IRI) as hasil FROM keping_jalan where NO_RUAS = ".$no_ruas." AND NILAI_IRI >= 0 AND NILAI_IRI < 4");
		foreach ($tot_km_hijau->result() as $row) {
			$data['tot_km_hijau'] = $row->hasil;
		}
		$this->load->view('cetak_keping', $data);
	}

    function cek_validasi() {
        // Setting Rules
        // $this->form_validation->set_rules('nama_santri', 'Nama Santri', 'required');
        // $this->form_validation->set_rules('munakosah', 'No. Induk', 'required');

        // //Setting Error Message
        // $this->form_validation->set_message('required', 'Field %s harus diisi.');

        // // Setting Delimiter
        // $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }
	
	
	
	//test
	function readExcel()
	{
        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file('tes.csv');

        $data['csvData'] =  $result;
        $this->load->view('view_csv', $data);  
	}

	

}
